package app.server.project.core.json;

import app.server.project.core.constants.CfgDef;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.watch.SimpleWatcher;
import cn.hutool.core.io.watch.WatchMonitor;
import cn.hutool.json.JSONUtil;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.util.HashMap;

@Component
@Slf4j
public class JsonMgr {


    @Value("${" + CfgDef.FilePath + "}")
    private String filePath;
    @Autowired
    private ApplicationContext applicationContext;

    @PostConstruct
    public void init() {
        this.applicationContext.getBeansOfType(JsonLife.class).forEach((k, v) -> {
            File file = new File(this.filePath + v.getClassType().getSimpleName().toLowerCase() + ".json");
            String jsonStr = FileUtil.readString(file, "UTF-8");
            log.info("==========读取到{}.json===={}", v.getClassType().getSimpleName().toLowerCase(), jsonStr);
            var jsonObject = JSONUtil.toBean(jsonStr, HashMap.class);
            v.init(jsonObject);
            v.load(jsonObject);
            //监控文件变化,然后重新加载文件
            WatchMonitor.createAll(file, new SimpleWatcher() {
                @Override
                public void onModify(WatchEvent<?> event, Path currentPath) {
                    String loadStr = FileUtil.readString(file, "UTF-8");
                    log.info("==========重新加载====读取到json====:{}", loadStr);
                    var reloadData = JSONUtil.toBean(loadStr, HashMap.class);
                    v.init(reloadData);
                    v.load(reloadData);
                }
            }).start();
        });
    }


}
